/**
 * 
 */
package com.snapp.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.snapp.util.object.DBObject;
import com.snapp.util.object.model.ObjectModel;

/**
 * @author Kile
 *
 */

public class Statics {
	private static Logger logger = Logger.getLogger(Statics.class);

	public static final String STATICS_TABLE = "Statics";
	
	public synchronized static ObjectModel get(String mnemonic) {
		return Cache.INSTANCE.objectIndex.get(mnemonic);
	}
	
	public synchronized static Vector<ObjectModel> list(String mnemonic) {
		return Cache.INSTANCE.listIndex.get(mnemonic);
	}
	
	private synchronized static void add(ObjectModel model) {
		Cache.INSTANCE.objectIndex.put(model.getBean().getPropertyString("mnemonic"), model);
	}
	private synchronized static void add(String mnemonic, Vector<ObjectModel> list) {
		Cache.INSTANCE.listIndex.put(mnemonic, list);
	}

	public synchronized static void load() {
		// object for gathering top-level types
		DBObject topLevelTypes = new DBObject();
		
		// set table name
		topLevelTypes.setObjectName(STATICS_TABLE);
		
		// read-only
		topLevelTypes.setReadOnly(true);
		
		// list the types in the start-up catalog
		Vector<ObjectModel> types = topLevelTypes.list("parent=0 and status=1");
		
		// populate catalog cache
		populate(types);
	
	}
	/**
	 * 
	 * @param types
	 */
	private synchronized static void populate(Vector<ObjectModel> types) {
		/*
		 *  for each type, test for children and add list if needed
		 */
		Iterator<ObjectModel> itr = types.iterator();
		while (itr.hasNext()) {
			// next types object
			ObjectModel pob = itr.next();
			
			// add this object to the types index
			add(pob);
			logger.info("Adding Static Bean: "+pob.getBean().getPropertyString("name"));
			
			// get child list
			Vector<ObjectModel> ch = pob.list("parent="+pob.getBean().getPropertyString("id")+" and status=1");
			
			// add list and recurse if it has children
			if (ch.size() > 0) { 
				// show the dev crew
				logger.info("Adding Static List: "+pob.getBean().getPropertyString("name"));
				// add list
				add(pob.getBean().getPropertyString("mnemonic"), ch);
				// recurse
				populate(ch);
			}
			
		}

	}
	
	private enum Cache {
		INSTANCE;
		
		public HashMap<String,ObjectModel> objectIndex = new HashMap<String,ObjectModel>();
		public HashMap<String,Vector<ObjectModel>> listIndex = new HashMap<String, Vector<ObjectModel>>();
		
	}

}
